*! v 1.01 2023/9/26 17:18
*! Yujun Lian, arlionn@163.com

* o Goal: get {DOI} from a string using regular expression

* o -------------- Usage and Examples -------------

*   > Extract {DOI} from string
*    . get_doi "Zhu, Y., 2023, FRL, ... doi.org/10.1016/j.frl.2023.103973"
*    . local doi "`r(doi)'"

*   > check whether the {DOI} specified is valid 
*    . capture noi get_doi "doi.org/10.1016/j.frl.2023.103973"

*   > check validity of {DOI}, and get return value
*    . capture get_doi "10. 10-16/j.frl.2023.103973"
*    . if `r(valid)'=0{dis as error xxx}

* o ------------------------------------------------  

cap program drop get_doi
program define get_doi, rclass
version 14

syntax anything(everything) [, NODisplay]

    local regex "10\.[\d]{4,}/[^\s]+[\d]"  // regular expression of {DOI}
    
    local m = ustrregexm(`"`anything'"', "`regex'")
    
    if `m'==0{
        dis as error "Can not find valid {DOI}, please check."
        return scalar valid = `m'
        exit 
    }
    else{
        local doi = ustrregexs(0)
        if "`nodisplay'" == ""{
            dis "`doi'"
        }
    
        return local  doi = "`doi'"  
        return scalar valid = `m'  // 1 = get valid DOI, 0 = otherwise
    }

end 



/*

*------------ test ------------ not part of Program, just for testing 

  set trace on 

local DOI   ""10.1257/aer.109.4.1197""     // double """"
// local DOI "10.1016/j.eneco.2022.106017" // many authors, special characters 
// local DOI "10.1162/rest.90.3.592"       // RES
// local DOI "10.1177/1536867X231175332"   // SJ 23-2
// local DOI "10.3969/j.issn.1000-6249.2007.01.003"  // Chinese article
// local DOI "10.2139/ssrn.3765862"          // SSRN   
// local DOI "10.48550/arXiv.1301.3781"      // arXiv
// local DOI "10.1111/j.1467-629X.2010.00375.x"
local DOI `"Zhu, Y., K. Huang, **2023**, FRL, 55: 10.3973. [-Link-](https://doi.org/10.1016/j.frl.2023.103973), [-PDF-](https://sci-hub.ren/10.1016/j.frl.2023.103973)"'
// local DOI "Salgado (2003.10.2344). Use of. SJ, 3(2), 133–147. doi:10.1177/1536867x0300300203  "
  local DOI "10. 1257/aer.109-4.1197"  // invalid DOI
  local DOI "10.1257//aer.109-4.1197"  // invalid DOI, can not be detected, to be done??
  
  get_doi "`DOI'"
  get_doi "`DOI'", nodis
  ret list 
  
*/
  







